<template>
  <div class="default-main ba-table-box">
    <div class="block">
      <div class="table-block">
        <el-alert class="ba-table-alert"
                  v-if="baTable.table.remark"
                  :title="baTable.table.remark"
                  type="info"
                  show-icon />
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
          <template #campaign>
            <el-autocomplete v-model="baTable.comSearch.form['campaign']"
                             :fetch-suggestions="querySearch"
                             :trigger-on-focus="false"
                             clearable
                             placeholder="搜索名称/ID"
                             value-key="label"
                             @select="handleSelect"
                             @change="handleChange" />
          </template>
          <template #time>
            <el-date-picker v-model="baTable.comSearch.form['time']"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :shortcuts="shortcuts"
                            value-format="YYYY-MM-DD" />
          </template>
        </TableHeader>

        <el-row style="margin: 10px 0;"
                :gutter="10">
          <el-col :span="1.5">
            <el-button type="warning"
                       @click="exportExcelOperate"
                       :loading="state.buttonLoading"
                       v-if="baTable.auth('export')">
              <Icon :color="'#ffffff'"
                    name="el-icon-Position" />导出
            </el-button>
          </el-col>
        </el-row>

        <Table show-summary
               :summary-method="getSummaries"></Table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, provide } from 'vue'
import baTableClass from '/@/utils/baTable'
// import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { baTableApi, fileDownload } from '/@/api/common'
import Cookies from 'js-cookie'
import { useI18n } from 'vue-i18n'
import { ElMessageBox } from 'element-plus'
import { exportExcel } from '/@/api/backend/advertisement/TikAccountData'

defineOptions({
    name: 'advertisement/TikAccountData',
})
const { t } = useI18n()
const state: {
    buttonLoading: boolean
} = reactive({
    buttonLoading: false
})
const shortcuts = [
    {
        text: '昨天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '过去7天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '过去30天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
        }
    }
]
const inputText = ref()
const querySearch = (queryString: string, cb: any) => {
  cb([
    {
        value: 1,
        label: '推广系列名称/ID'
    },
    {
        value: 2,
        label: '广告名/ID'
    },
  ])
}

const baTable = new baTableClass(
    new baTableApi('/advertisement/TikAccountData/'),
    {
        column: [
        {
                label: '运营',
                prop:  'campaign',
                operator: false, 
                comSearchRender:'slot',
                comSearchSlotName: 'campaign',
                show: false
            },
            {
                label: '时间',
                prop:  'time',
                operator: '=', 
                comSearchRender:'slot',
                comSearchSlotName: 'time',
                show: false
            },
            {  
                label: '账户名称', 
                prop: 'advertiser_name', 
                align: 'center',
                operator: true,
                operatorPlaceholder: t('Please input field')
            },
            {   
                label: '推广系列名称', 
                prop: 'campaign_name', 
                align: 'center',
                operator: true,
                operatorPlaceholder: t('Please input field')
            },
            {   
                label: '广告名称', 
                prop: 'ad_name', 
                align: 'center',
                operator: true,
                operatorPlaceholder: t('Please input field')
            },
            {   
                label: '日期', 
                prop: 'stat_time_day', 
                align: 'center',
                operator: false
            },
            {   
                label: '总消耗', 
                prop: 'spend', 
                align: 'center',
                operator: false
            },
            {   
                label: '总收入(商店)', 
                prop: 'total_onsite_shopping_value', 
                align: 'center',
                operator: true,
                operatorPlaceholder: t('Please input field')
            },
            {   
                label: '付费数(商店)', 
                prop: 'conversion', 
                align: 'center',
                operator: false
            },
            {   
                label: '实时转化', 
                prop: 'real_time_conversion', 
                align: 'center',
                operator: false
            },
            {   
                label: 'ROAS(商店)', 
                prop: 'onsite_shopping_roas', 
                align: 'center',
                operator: false
            }
        ],
        dblClickNotEditColumn: ['all']
    },
    {
        defaultItems: {
            status: '1',
        }
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

const getSummaries = (param:any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column:any, index:any) => {
    const key = column.columnKey
    switch(key){
        case 'advertiser_name':
            sums[index] = `总计: ${String(baTable.table.total)}条`
            break
        case 'spend':
            sums[index] = `${baTable.table.extend?.spend} USD`
            break
        case 'total_onsite_shopping_value':
            sums[index] = `${baTable.table.extend?.total_onsite_shopping_value} USD`
            break
        case 'conversion':
            sums[index] = `${baTable.table.extend?.conversion}`
            break
        case 'onsite_shopping_roas':
            sums[index] = `${baTable.table.extend?.onsite_shopping_roas}`
            break
        case 'real_time_conversion':
            sums[index] = `${baTable.table.extend?.real_time_conversion}`
            break
        default:
            sums[index] = ''
    }
  })
  return sums
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
        state.buttonLoading = false
        baTable.table.loading = false
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const handleSelect = (item: Record<string, any>) => {
    baTable.comSearch.form['campaign'] = inputText.value
    const comSearchData: Array<any> = baTable.table.filter?.search || []
    comSearchData.push({
        field: 'campaign',
        val: inputText.value,
        operator: '',
        render: ''
    })
    comSearchData.push({
        field: 'type',
        val: item.value,
        operator: '',
        render: ''
    })
    baTable.onTableAction('com-search', comSearchData)
}

const handleChange = (value: string | number) => {
    inputText.value = value
}

</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-input__wrapper){
    width: initial;
}
</style>
